<template>
  <el-button type="primary" style="margin-bottom: 10px;" @click="open()">添加</el-button>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" width="50" />
    <el-table-column prop="commodityName" label="商品名称"  />
    <el-table-column prop="traceabilityBatch" label="生产批次" />
    <el-table-column prop="traceabilityShelf" label="保质期" />
    <el-table-column prop="traceaDocuments" label="生产许可证" />
    <el-table-column prop="manufacturers" label="生产企业" />
    <el-table-column prop="traceabilityPhoto" label="照片" >
      <template v-slot="{ row }">
        <img :src="row.traceabilityPhoto" style="width: 100px; height: 100px" />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="350">
      <template v-slot="scope">
        <el-button type="primary" @click="del(scope.row)" >删除</el-button>
        <el-button type="danger" @click="open(scope.row)" >修改</el-button>
        <el-button type="success" @click="exportQRCode(scope.row)">导出溯源码</el-button>
        <el-button type="warning" @click="jumpe(scope.row)" >详细</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-model:current-page="from.pageIndex"
      v-model:page-size="from.pageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="from.totalCount"
    />

    <el-dialog v-model="logic.isopen" :title="logic.isTitle" width="500">
    <el-form :model="data">
      <el-form-item label="商品" >
        <el-select v-model="data.commodityId" >
          <el-option v-for="item in Commodity" :label="item.commodityName" :value="item.commodityId" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次" >
        <el-input v-model="data.traceabilityBatch"  />
      </el-form-item>
      <el-form-item label="保质期" >
        <el-input v-model="data.traceabilityShelf"  />
      </el-form-item>
      <el-form-item label="生产许可证" >
        <el-input v-model="data.traceaDocuments"  />
      </el-form-item>
      <el-form-item label="生产企业" >
        <el-input v-model="data.manufacturers"  />
      </el-form-item>
      <el-form-item label="照片" >
        <el-upload
    class="avatar-uploader"
    action="https://localhost:44393/api/one/UploadPhoto"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="data.traceabilityPhoto" :src="data.traceabilityPhoto" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.isopen=false">取消</el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">

import { ref,reactive,onMounted,watch} from 'vue';
import axiox from 'axios';
import { ElMessage,ElMessageBox  } from 'element-plus';
import {useCounterStore} from '@/stores/counter';
import { useRouter,useRoute } from 'vue-router';
const router =useRouter();
const route =useRoute();

import { da, ro } from 'element-plus/es/locale/index.mjs';
const Store = useCounterStore();

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
//数据对象
const data=reactive({
  traceabilityId: 0,
  commodityId: 0,
  traceabilityBatch: "",
  traceabilityShelf: "",
  traceaDocuments: "",
  manufacturers: "",
  traceabilityPhoto: ""
})
//逻辑对象
const logic=reactive({
  isopen:false,
  isadd:true,
  isTitle:"",
})
///打开弹窗
const open=(row:any)=>{
logic.isopen=true;
if(row==null ){
  logic.isadd=true;
  logic.isTitle="添加";
  data.traceabilityId=0;
  data.commodityId=0;
  data.traceabilityBatch="";
  data.traceabilityShelf="";
  data.traceaDocuments="";
  data.manufacturers="";
  data.traceabilityPhoto="";
}
else
{
  logic.isTitle="修改";
  logic.isadd=false;
  data.traceabilityId=row.traceabilityId;
  data.commodityId=row.commodityId;
  data.traceabilityBatch=row.traceabilityBatch;
  data.traceabilityShelf=row.traceabilityShelf;
  data.traceaDocuments=row.traceaDocuments
  data.manufacturers=row.manufacturers;
  data.traceabilityPhoto=row.traceabilityPhoto;
}
}

const exportQRCode = (row:any) => {
  axiox.post("https://localhost:44393/api/one/ExportQRCode", row, {
    responseType: 'blob'
  }).then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'qrcode.png');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('二维码导出成功');
  }).catch(() => {
    ElMessage.error('二维码导出失败');
  });
};




//保存和修改
const save=()=>{
  if(logic.isadd){
  axiox.post("https://localhost:44393/api/one/AddTraceability",data).then(res=>{
    if(res.data.code == 200){
      ElMessage.success(res.data.message);
      getdata();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
  })
  }
  else
  {
  axiox.post("https://localhost:44393/api/one/UpdateTraceability",data).then(res=>{
    if(res.data.code == 500){
      ElMessage.success(res.data.message);
      getdata();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
  })
  }
}
//表格数据
const tableData=ref([]);

const from=reactive({
  pageSize: 3,
  pageIndex: 1,
  totalCount:0,
  totalPage:0
})
const getdata=()=>{
axiox.get("https://localhost:44393/api/one/ShowTraceability",{
  params:{
    pageSize:from.pageSize,
    pageIndex:from.pageIndex
  } 
}).then(res=>{
  if(res.data.code == 300){
    tableData.value=res.data.data.list;
    from.totalCount=res.data.data.totalCount;
    from.totalPage=res.data.data.totalPage;
    return;
  }
  else
  {
    ElMessage.error(res.data.message);
  }
})
}
watch(from,()=>{
  getdata();
})
//商品数据
const Commodity=ref<any>([]);

const getCommodity=()=>{
  axiox.get("https://localhost:44393/api/one/ShowCommunity").then(res=>{
    if(res.data.code == 300){
      Commodity.value=res.data.data;
      return;
    }
    else
    {
      ElMessage.error(res.data.message);
    }
  })
}
onMounted(()=>{
  getCommodity();
  getdata();
})
//删除
const del=(row:any)=>{
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axiox.post("https://localhost:44393/api/one/DelTraceability",row).then(res=>{
        if(res.data.code == 400){
          ElMessage.success(res.data.message);
          getdata();

        }
        else
        {
          ElMessage.error(res.data.message);
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}


 ///上传图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  data.traceabilityPhoto = "https://localhost:44393"+response;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const jumpe=(row:any)=>{
  router.push({
    name:"Detail",
    query:{
      id:row.traceabilityId
    }
  })

}

</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>